package com.njworkorder.Handler;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.njworkorder.Controller.JhWorkspaceApiController;
import com.njworkorder.Entity.DiseaseReportRecord;
import com.njworkorder.Entity.MeteringUse;
import com.njworkorder.Entity.PatrolInfo;
import com.njworkorder.Service.DiseaseReportRecordService;
import com.njworkorder.Service.MeteringUseService;
import com.njworkorder.Service.PatrolInfoService;
import com.njworkorder.Service.TasksNumService;
import com.njworkorder.Utils.WebClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Component
public class ScheduledTasks {

    private final JhWorkspaceApiController jhWorkspaceApiController;
    private final TasksNumService tasksNumService;
    private final MeteringUseService meteringUseService;
    private final DiseaseReportRecordService diseaseReportRecordService;
    private final PatrolInfoService patrolInfoService;
    public ScheduledTasks(JhWorkspaceApiController jhWorkspaceApiController,
                          TasksNumService tasksNumService,
                          MeteringUseService meteringUseService,
                          DiseaseReportRecordService diseaseReportRecordService,
                          PatrolInfoService patrolInfoService) {
        this.jhWorkspaceApiController = jhWorkspaceApiController;
        this.tasksNumService = tasksNumService;
        this.meteringUseService = meteringUseService;
        this.diseaseReportRecordService = diseaseReportRecordService;
        this.patrolInfoService = patrolInfoService;
    }

    @Scheduled(cron = "${my-task.cron1}")
    public void scheduleTaskWithCronExpression() {
        log.info("定时获取巡查任务数开始");
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate today = LocalDate.now();
            String sTime = today.format(formatter);
            LocalDate tomorrow = today.plusDays(1);
            String eTime = tomorrow.format(formatter);

            String format = String.format("%s - %s", sTime, eTime);

            Map<String, String> pam = new HashMap<>();
            pam.put("begin", format);
            pam.put("orgCode", "491");
            String block = WebClientUtil.get(JhWorkspaceApiController.url + "/openapi/getSpecialCountByStartEndTime", pam, jhWorkspaceApiController.getHeaderMap(), String.class).block();
            JSONObject jsonObject = JSONObject.parseObject(block);
            if (jsonObject != null) {
                int result = jsonObject.getIntValue("result");
                tasksNumService.updateTasksNum(result);
            }
        } catch (Exception e) {
            log.error("定时请求获取巡查任务数(次)出错:{}", e.getMessage());
        }
    }

    //定时获取清单使用量数据
    @Scheduled(cron = "${my-task.cron2}")
    public void scheduleTaskWithCronExpression2() throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate today = LocalDate.now();
        LocalDate localDate = today.minusDays(1);
        String sTime = localDate.format(formatter);

        //sTime = "2025-07-28";

        Map<String, String> body = new HashMap<>();
        body.put("startTime", sTime + " 00:00:00");
        body.put("endTime", sTime + " 23:59:59");
        body.put("workAreaQsId", "ff80818196afee370196afef7f030002");
        body.put("roadCode", "G2");
        String block = WebClientUtil.post("https://qianhe-uzising.lingyunzhineng.com/qsyhxc/openapi/getEngineeringCount", body, jhWorkspaceApiController.getHeaderMap(), String.class).block();
        JSONObject jsonObject = JSONObject.parseObject(block);
        if (jsonObject != null) {
            JSONArray data = jsonObject.getJSONArray("result");

            List<MeteringUse> meteringUseList = new ArrayList<>();
            MeteringUse meteringUse;
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObj = data.getJSONObject(i);
                meteringUse = new MeteringUse();
                meteringUse.setIsDate(sdf.parse(jsonObj.getString("date")));
                meteringUse.setFVcRoadcode(jsonObj.getString("roadCode"));
                meteringUse.setPricingType(Objects.equals(jsonObj.getString("pricingMode"), "总价") ? "1" : Objects.equals(jsonObj.getString("pricingMode"), "单价") ? "2": "3");
                meteringUse.setProjectCode(jsonObj.getString("projectCode"));
                meteringUse.setProjectName(jsonObj.getString("projectName"));
                meteringUse.setNum(jsonObj.getDouble("num"));
                meteringUse.setCreateTime(new Date());

                meteringUseList.add(meteringUse);
            }
            meteringUseService.saveBatch(meteringUseList);

        }
    }


    //定时获取京沪病害上报记录信息
    @Scheduled(cron = "${my-task.cron3}")
    public void scheduleTaskWithCronExpression3() throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate today = LocalDate.now();
        LocalDate localDate = today.minusDays(1);
        String sTime = localDate.format(formatter);

        Map<String, String> body = new HashMap<>();
        body.put("startTime", sTime + " 00:00:00");
        body.put("endTime", sTime + " 23:59:59");

        String block = WebClientUtil.post("https://qianhe-uzising.lingyunzhineng.com/qsyhxc/openapi/getDisInfo", body, jhWorkspaceApiController.getHeaderMap(), String.class).block();
        JSONObject jsonObject = JSONObject.parseObject(block);
        if (jsonObject != null) {
            JSONArray data = jsonObject.getJSONArray("result");

            List<DiseaseReportRecord> dsrList = new ArrayList<>();
            DiseaseReportRecord diseaseReportRecord;
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObj = data.getJSONObject(i);
                diseaseReportRecord = new DiseaseReportRecord();
                diseaseReportRecord.setReporterName(jsonObj.getString("reporterName"));
                diseaseReportRecord.setReporterTime(sdf.parse(jsonObj.getString("reporterTime")));
                diseaseReportRecord.setWorkAreaName(jsonObj.getString("workAreaName"));
                diseaseReportRecord.setRoadCode(jsonObj.getString("roadCode"));
                diseaseReportRecord.setStartKm(jsonObj.getDouble("startKm"));
                diseaseReportRecord.setStartMet(jsonObj.getDouble("startM"));
                diseaseReportRecord.setDisName(jsonObj.getString("disName"));
                dsrList.add(diseaseReportRecord);
            }
            diseaseReportRecordService.saveBatch(dsrList);
        }
    }

    //定时查询京沪时间范围内巡查次数和⾥程
    @Scheduled(cron = "${my-task.cron4}")
    public void scheduleTaskWithCronExpression4() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate today = LocalDate.now();
        LocalDate localDate = today.minusDays(1);
        String sTime = localDate.format(formatter);

        Map<String, String> body = new HashMap<>();
        body.put("startTime", sTime + " 00:00:00");
        body.put("endTime", sTime + " 23:59:59");
        body.put("workAreaQsId", "ff80818196afee370196afef7f030002");

        String block = WebClientUtil.post("https://qianhe-uzising.lingyunzhineng.com/qsyhxc/openapi/getPtrlTaskThridInfo", body, jhWorkspaceApiController.getHeaderMap(), String.class).block();
        JSONObject jsonObject = JSONObject.parseObject(block);
        if (jsonObject != null) {
            JSONArray data = jsonObject.getJSONArray("result");

            List<PatrolInfo>  patrolInfoList = new ArrayList<>();
            PatrolInfo  patrolInfo;
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObj = data.getJSONObject(i);
                patrolInfo  = new PatrolInfo();
                patrolInfo.setPatrolType(jsonObj.getDouble("patrolType"));
                patrolInfo.setPatrolTypeName(jsonObj.getString("patrolTypeName"));
                patrolInfo.setTotalTaskCount(jsonObj.getIntValue("totalTaskCount"));
                patrolInfo.setTotalMileage(jsonObj.getDouble("totalMileage"));
                patrolInfo.setPatrolDate(sdf.parse(jsonObj.getString("date")));
                patrolInfoList.add(patrolInfo);
            }

            patrolInfoService.saveBatch(patrolInfoList);
        }
    }

}